#include "../inc/main.h"
#include "../inc/TCP.h"

#include <head.h>

// 定义互斥锁
pthread_mutex_t mutex;


// 定义消息协议



void *Client_dispose(void *arg)
{
    Client_link_up *head = (Client_link_up *)arg;

    // 搜索自己的结点
    Client_link_node * node = link_Client_find_id(head->link , head->id);
    
    // 群发结点
    Client_link_node * ptr = head->link->next;

    // 接收缓冲区
    char buf[1024];
    int recv_len;

    // 循环接收数据
    while (1)
    {
        recv_len = recv(node->Client_sofd, buf, sizeof(buf) - 1, 0);  // 留出一个位置给 '\0'
        if (recv_len > 0)
        {
            buf[recv_len] = '\0';  // 确保字符串以 '\0' 结尾

            // 打印客户端的 IP 地址和端口号
            printf("ip[%s] port[%d] = [%s]\n", inet_ntoa(node->Client_addr.sin_addr), ntohs(node->Client_addr.sin_port), buf);

            // 群发
            pthread_mutex_lock( &mutex );

            ptr = head->link->next;
            
            for (size_t i = 0; i < head->link->len; i++)
            {
                if (ptr->id != node->id)
                {
                    send( ptr->Client_sofd , buf , strlen(buf) , 0 );
                }
                ptr = ptr->next;
            }
            pthread_mutex_unlock( &mutex );
            
        }

        else if (recv_len == 0)
        {
            // 客户端关闭连接
            printf("Client disconnected: ip[%s] port[%d]\n", inet_ntoa(node->Client_addr.sin_addr), ntohs(node->Client_addr.sin_port));
            break;  // 退出循环，关闭连接
        }

        else
        {
            // 发生错误
            perror("recv");
            break;
        }
    }

    // 关闭客户端套接字
    close(node->Client_sofd);
    pthread_exit(NULL);
}

int main(int argc, char const *argv[])
{
    TCP tcp = tcp_init();

    // 服务器相关参数
    struct sockaddr_in Server_addr = tcp.Server_addr;
    int server_sockfd = tcp.server_sockfd;
    socklen_t server_len = sizeof(Server_addr);

    // 客户端相关参数
    struct sockaddr_in client_addr;
    int client_sockfd;
    socklen_t client_len = sizeof(client_addr);

    // 客户端链表 初始化头节点
    int id = -1; // 用户ID
    Client_link *Cli_link = link_Client_init();
    Client_link_node node;

    // 数据库处理
    sqlite3 *sql_db = sqlite3_init_log_in();

    // 线程相关 变量
    pthread_t thread_Tid[1024];

    // 连接成功 创建线程
    Client_link_up * link_arg = (Client_link_up *) malloc(sizeof(Client_link_up));

    link_arg->link = Cli_link;

    // 互斥锁初始化
    if(0 != pthread_mutex_init( &mutex , NULL ))
    {
        printf("Mutex init failed\n");
        return 1;
    }


    while (1)
    {
        // 开启连接
        client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_addr, &client_len);
        if (client_sockfd == -1)
        {
            ERRLOG("accept");
            exit(-1);
        }

        // 为结点添加信息
        node.Client_addr = client_addr;
        node.client_len = sizeof(client_addr);
        node.Client_sofd = client_sockfd;
        node.id = ++id;

        // 插入结点到链表 并接收当前连接的结点
        Client_link_node *new_node = link_Client_insert(Cli_link, node);

        link_arg->id = id;
        

        pthread_create( &thread_Tid[id], NULL, Client_dispose, (void *)link_arg);

        pthread_detach(thread_Tid[id]);
    }

    // 销毁互斥锁
    pthread_mutex_destroy( &mutex );

    close(server_sockfd);

    return 0;
}
